{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '0'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate,\n",
    "                beam_width = 5):\n",
    "        \n",
    "        def cells(size_layer = size_layer, reuse=False):\n",
    "            return tf.nn.rnn_cell.GRUCell(size_layer, reuse=reuse)\n",
    "        \n",
    "        def attention(encoder_out, seq_len, reuse=False):\n",
    "            attention_mechanism = tf.contrib.seq2seq.BahdanauAttention(num_units = size_layer, \n",
    "                                                                    memory = encoder_out,\n",
    "                                                                    memory_sequence_length = seq_len)\n",
    "            return tf.contrib.seq2seq.AttentionWrapper(\n",
    "            cell = tf.nn.rnn_cell.MultiRNNCell([cells(reuse=reuse) for _ in range(num_layers)]), \n",
    "                attention_mechanism = attention_mechanism,\n",
    "                attention_layer_size = size_layer)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        encoder_out = tf.nn.embedding_lookup(embeddings, self.X)\n",
    "        \n",
    "        for n in range(num_layers):\n",
    "            (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n",
    "                cell_fw = cells(size_layer // 2),\n",
    "                cell_bw = cells(size_layer // 2),\n",
    "                inputs = encoder_out,\n",
    "                sequence_length = self.X_seq_len,\n",
    "                dtype = tf.float32,\n",
    "                scope = 'bidirectional_rnn_%d'%(n))\n",
    "            encoder_out = tf.concat((out_fw, out_bw), 2)\n",
    "        bi_state = tf.concat((state_fw,state_bw), -1)\n",
    "        encoder_state = tuple([bi_state] * num_layers)\n",
    "        \n",
    "        main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        dense = tf.layers.Dense(vocab_size)\n",
    "        \n",
    "        with tf.variable_scope('decode'):\n",
    "            decoder_cells = attention(encoder_out, self.X_seq_len)\n",
    "            states = decoder_cells.zero_state(batch_size, tf.float32).clone(cell_state=encoder_state)\n",
    "\n",
    "            training_helper = tf.contrib.seq2seq.TrainingHelper(\n",
    "                    inputs = tf.nn.embedding_lookup(embeddings, decoder_input),\n",
    "                    sequence_length = self.Y_seq_len,\n",
    "                    time_major = False)\n",
    "            training_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                    cell = decoder_cells,\n",
    "                    helper = training_helper,\n",
    "                    initial_state = states,\n",
    "                    output_layer = dense)\n",
    "            training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                    decoder = training_decoder,\n",
    "                    impute_finished = True,\n",
    "                    maximum_iterations = tf.reduce_max(self.Y_seq_len))\n",
    "            self.training_logits = training_decoder_output.rnn_output\n",
    "        \n",
    "        with tf.variable_scope('decode', reuse=True):\n",
    "            encoder_out_tiled = tf.contrib.seq2seq.tile_batch(encoder_out, beam_width)\n",
    "            encoder_state_tiled = tf.contrib.seq2seq.tile_batch(encoder_state, beam_width)\n",
    "            X_seq_len_tiled = tf.contrib.seq2seq.tile_batch(self.X_seq_len, beam_width)\n",
    "            decoder_cell = attention(encoder_out_tiled, X_seq_len_tiled, reuse=True)\n",
    "            states = decoder_cell.zero_state(batch_size * beam_width, tf.float32).clone(\n",
    "                    cell_state = encoder_state_tiled)\n",
    "            predicting_decoder = tf.contrib.seq2seq.BeamSearchDecoder(\n",
    "                cell = decoder_cell,\n",
    "                embedding = embeddings,\n",
    "                start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n",
    "                end_token = EOS,\n",
    "                initial_state = states,\n",
    "                beam_width = beam_width,\n",
    "                output_layer = dense,\n",
    "                length_penalty_weight = 0.0)\n",
    "            predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = predicting_decoder,\n",
    "                impute_finished = False,\n",
    "                maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n",
    "            self.fast_result = predicting_decoder_output.predicted_ids[:, :, 0]\n",
    "        \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From <ipython-input-7-c1ef8d23b1df>:12: GRUCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.GRUCell, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-c1ef8d23b1df>:40: bidirectional_dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.Bidirectional(keras.layers.RNN(cell))`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:464: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:559: Layer.add_variable (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.add_weight` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:565: calling Constant.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:575: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:244: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "WARNING:tensorflow:From <ipython-input-7-c1ef8d23b1df>:19: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/contrib/seq2seq/python/ops/beam_search_decoder.py:971: to_int64 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[18140, 18140, 18140, 18140, 18538, 18538, 25642, 25642, 25642,\n",
       "         25642, 25642, 25642,  5822, 13819,  7190,  5822,  5822,  5822,\n",
       "          5822,  5822,  5822,  5822, 14383, 14383, 14383, 14383, 14383,\n",
       "         14383, 31192, 31192, 31192, 31192, 12526, 12526, 12526, 12526,\n",
       "         12526,  8800,  8800,  8800, 28067, 28067, 28067,  6796,  6796,\n",
       "          6796,  6796,  6796,  6796,  6796,  6796,  6796,  6796, 16628,\n",
       "         20674, 20674, 20674, 20674, 20674, 16628,  5393,  5393,  5393,\n",
       "          5393,  5393,  3229,  3229,  3229,  3229,  3229,  3229,  3229],\n",
       "        [17380,  1074, 14817, 14817, 14817, 14817, 14817, 14817, 14817,\n",
       "          1122,  1122, 16566, 16566, 16566, 16566, 16566, 16566, 16566,\n",
       "         24158, 28048, 28048, 23610, 23610, 23610, 21941, 21941, 11793,\n",
       "         11793, 11793, 19250, 19250, 19250, 19250, 12709, 12709, 12709,\n",
       "           319, 24797, 14270, 14270, 30986, 30986, 30986, 11559, 11559,\n",
       "         11559, 11559, 11559, 11559, 29029, 29029, 29029, 29029, 27680,\n",
       "         27680, 27680, 16100, 16100, 16100, 19772, 19772,  8395,  8395,\n",
       "          8395,  8395, 30167, 15547, 15547,  9121,  9121,  9121,  9121],\n",
       "        [ 3383,  3383, 29262, 16672, 18901, 18901, 18901, 18901, 25906,\n",
       "         15420, 15420,  1544, 25001, 25001, 10331, 10331, 10331, 13048,\n",
       "         18915, 18915, 24900, 24900, 24900, 24900, 24900,  1091,  1091,\n",
       "          1091, 29541, 29541, 29541,  9739,  9739,  9739,  9739,  8630,\n",
       "         24178, 24178, 18954, 18954, 18954, 28012, 28012, 28012,  4909,\n",
       "         22189, 22189, 22189, 29735, 29735, 29735, 29735, 20393, 20393,\n",
       "         20393,  3663,  3663,  3663,  3663,  3663,  3663,  2790,  2790,\n",
       "          2790,  2790,  7288,  7288,  7288,  7288,  7288,  3852,  3852],\n",
       "        [23769, 23769, 23769, 23769,  2938,  2938,  2938,  2938, 29517,\n",
       "         29517, 29019, 29019, 29019, 29019, 29019, 29019, 29019, 29019,\n",
       "          2081,  7922,  7922,  7922, 28400, 28400, 28400, 28400, 31007,\n",
       "         21846, 21846, 21846, 21846, 30198, 30198, 30198,     5,     5,\n",
       "             5,     5,     5,     5,     5,     5,     5, 16460, 22531,\n",
       "         13416, 13416, 13416, 13416, 13416, 13416, 13416,    10, 13863,\n",
       "         13863, 13863, 13863, 13863, 13416, 12854, 12854, 12854, 12854,\n",
       "         12854, 30945, 30815, 30815, 30815, 30815, 30945, 30945, 18687],\n",
       "        [ 4022,  4022, 19580, 20005, 20005, 20005, 20005, 18837, 18837,\n",
       "          7219,  7219,  5373, 18673, 23298, 18160, 18160, 18160, 23926,\n",
       "         23926, 23926, 23926, 19933, 19933, 19933, 19933, 19933, 29133,\n",
       "         29133, 29133,  9655, 29133,  9655,  9655,  9655,  3871,  3871,\n",
       "         11556,  5383, 22365, 22365, 22365, 22365, 22365, 22365,  1581,\n",
       "          1581,  1581, 28414, 28414, 28414,  2171,  6330,  6330,  6330,\n",
       "          6330,  1918,  1918,  9071,  9071, 27333, 27333, 22457, 22457,\n",
       "         22457, 22457, 22457, 12372, 12372, 12372, 12372, 12372, 28203],\n",
       "        [12301, 12301, 12301, 12301, 17963, 17963, 16843, 16843, 16843,\n",
       "         16843, 16843,  7101,  7101, 16843,  7101,  7101,  7101,  7101,\n",
       "          7101,  7101,  7101, 16843,   402,   402,   402, 24149, 24149,\n",
       "         19569, 19569, 19569, 19569, 19569, 19569,  7963,  7963,  7963,\n",
       "          7963, 18890, 18890, 18890,  9159,  9159,  9159,  9159,  9159,\n",
       "          9159,  9159,  9159,  9159,  8674,  8674,  8674,  8674,  8674,\n",
       "          8674,  8674,  8674,  8674,  8674, 20037, 20037, 26776, 26776,\n",
       "         26776, 26776, 26776, 26776, 18201, 18201, 18201, 18201, 26939],\n",
       "        [20181, 23988,  1683,  1683,  1683,  1683,  1683, 17091, 16021,\n",
       "         16021, 16021, 16021, 10841, 10841, 27910, 27910, 27910, 27910,\n",
       "          4626,  4626,  4626,  4626, 26328, 26328, 26328, 10217, 10217,\n",
       "          1135,  1135,  1135,  1135,  1135,  1135, 28421, 28421,  4415,\n",
       "          4415,  4415,  4415,  4415,  4415,  4415,  4415,  4415,  4415,\n",
       "          4415, 16277, 16277,  1424,  1424,  1424,  1424,  1424,  1424,\n",
       "         27993, 22766, 22766, 22766,  9386, 30514, 30514, 30514, 27356,\n",
       "          1963,  1963,  1963,  1963, 17758, 10770, 10770, 10770, 10770],\n",
       "        [31079, 31079, 31079, 25450, 25450, 25450, 22725,  8819,  8819,\n",
       "          8819, 29384, 29384,  3183, 12071, 12071, 12071, 12071, 12071,\n",
       "         12071, 14257, 17658, 10729, 10729, 10729, 10729, 10729, 10729,\n",
       "         10729,  2764,  2764,  2764, 10632, 10632, 10632, 10632, 10632,\n",
       "         10632, 10632, 16977, 16977, 16977, 16977, 16977, 16977,  8831,\n",
       "         16977,  8831,  8831,  8831,  8831, 15007, 15007, 15007, 23132,\n",
       "         29448, 29448, 29448, 29448, 15415, 15415, 15415, 15415, 15415,\n",
       "         15415, 15415, 15415, 15415, 15415, 15415, 15415,  2480,  2480],\n",
       "        [30349, 29392, 18761, 29738, 29738, 29738, 29738, 29738, 29738,\n",
       "         29738,  5029, 19882, 19882, 19882, 19882, 19882, 19882, 16846,\n",
       "         11590, 11590, 11590, 11590,  4653,  4653,  4653,  4653,  4653,\n",
       "         29297, 29297,  6060,  6060,  6060,  6060,  6060,  6060, 29133,\n",
       "         29133, 29133, 29133, 29133, 29133,  3488,  3488, 17236, 19089,\n",
       "         17236,  5137,  5137,  7242,  5137,  5137,  5137,  5137, 19882,\n",
       "         19882, 19882, 19882, 19882,  2795,  2795,  2795,  2795,  2795,\n",
       "          2795,  2795, 21894,  2795, 21894, 12287, 21894, 13759, 13759],\n",
       "        [25731, 10124, 22909, 22909, 22909, 22909, 22909,  9419, 29090,\n",
       "         29090, 29090, 29090, 29090,  1175,  3680,  3680, 17309, 17309,\n",
       "         17309, 17309,  6905, 26935, 26935, 26935, 26935, 16614, 16662,\n",
       "         26935, 16662, 16662, 16662, 16662, 10365, 10365, 10286, 10286,\n",
       "         10286, 10286, 25705,  5662,  5662,  5662,  5662,  5662, 30029,\n",
       "         30029, 30029,  6533,  6533,  6533,  6533,  6533,  4685,  4685,\n",
       "         18636, 18636, 18636, 18636, 30850, 12711, 12711,  1500,  9952,\n",
       "          9952,  1500, 15338, 15338, 15338, 15338, 15338, 10917, 10917]],\n",
       "       dtype=int32), 10.375526, 0.0]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:49<00:00,  1.88it/s, accuracy=0.379, cost=3.76]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.89it/s, accuracy=0.43, cost=3.19] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 4.996388, training avg acc 0.262639\n",
      "epoch 1, testing avg loss 3.664750, testing avg acc 0.387357\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:08<00:00,  1.84it/s, accuracy=0.49, cost=2.8]  \n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.97it/s, accuracy=0.484, cost=2.8] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 3.220631, training avg acc 0.433939\n",
      "epoch 2, testing avg loss 3.146085, testing avg acc 0.447851\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:08<00:00,  1.84it/s, accuracy=0.55, cost=2.27] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.98it/s, accuracy=0.522, cost=2.63]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 2.707036, training avg acc 0.492030\n",
      "epoch 3, testing avg loss 2.982374, testing avg acc 0.471500\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:07<00:00,  1.84it/s, accuracy=0.596, cost=1.96]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.98it/s, accuracy=0.532, cost=2.51]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 2.403955, training avg acc 0.528969\n",
      "epoch 4, testing avg loss 2.957712, testing avg acc 0.478877\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:09<00:00,  1.84it/s, accuracy=0.634, cost=1.7] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.97it/s, accuracy=0.554, cost=2.51]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 2.202244, training avg acc 0.554744\n",
      "epoch 5, testing avg loss 2.911584, testing avg acc 0.487681\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:08<00:00,  1.84it/s, accuracy=0.634, cost=1.64]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.98it/s, accuracy=0.495, cost=2.73]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 2.065565, training avg acc 0.572394\n",
      "epoch 6, testing avg loss 3.165898, testing avg acc 0.458562\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:08<00:00,  1.84it/s, accuracy=0.674, cost=1.46]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  4.00it/s, accuracy=0.57, cost=2.41] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 1.965397, training avg acc 0.585059\n",
      "epoch 7, testing avg loss 2.954776, testing avg acc 0.491022\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:08<00:00,  1.84it/s, accuracy=0.701, cost=1.31]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.97it/s, accuracy=0.554, cost=2.47]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 1.816127, training avg acc 0.608187\n",
      "epoch 8, testing avg loss 3.021922, testing avg acc 0.486905\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:07<00:00,  1.84it/s, accuracy=0.722, cost=1.23]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.98it/s, accuracy=0.559, cost=2.43]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 1.724728, training avg acc 0.621363\n",
      "epoch 9, testing avg loss 3.091577, testing avg acc 0.484528\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:07<00:00,  1.84it/s, accuracy=0.727, cost=1.18]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.97it/s, accuracy=0.57, cost=2.51] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 1.691283, training avg acc 0.624549\n",
      "epoch 10, testing avg loss 3.136711, testing avg acc 0.482967\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:08<00:00,  1.84it/s, accuracy=0.728, cost=1.08]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.98it/s, accuracy=0.548, cost=2.45]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 1.586424, training avg acc 0.642092\n",
      "epoch 11, testing avg loss 3.197130, testing avg acc 0.486990\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:07<00:00,  1.84it/s, accuracy=0.751, cost=1.02]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.96it/s, accuracy=0.532, cost=2.66]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 1.536515, training avg acc 0.649565\n",
      "epoch 12, testing avg loss 3.276606, testing avg acc 0.485312\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:08<00:00,  1.84it/s, accuracy=0.752, cost=0.972]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.96it/s, accuracy=0.511, cost=2.74]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 1.488943, training avg acc 0.656619\n",
      "epoch 13, testing avg loss 3.319370, testing avg acc 0.481459\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:08<00:00,  1.84it/s, accuracy=0.726, cost=1.09]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.97it/s, accuracy=0.522, cost=2.92]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 1.443303, training avg acc 0.663750\n",
      "epoch 14, testing avg loss 3.519753, testing avg acc 0.465299\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:08<00:00,  1.84it/s, accuracy=0.754, cost=0.99]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.95it/s, accuracy=0.532, cost=2.86]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 1.433057, training avg acc 0.664409\n",
      "epoch 15, testing avg loss 3.418456, testing avg acc 0.480460\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop:  77%|███████▋  | 1205/1563 [10:49<03:16,  1.82it/s, accuracy=0.692, cost=1.3] IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "minibatch loop: 100%|██████████| 1563/1563 [14:07<00:00,  1.84it/s, accuracy=0.737, cost=0.991]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.97it/s, accuracy=0.554, cost=3]   \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 1.352519, training avg acc 0.677794\n",
      "epoch 18, testing avg loss 3.609174, testing avg acc 0.475950\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop:  26%|██▌       | 410/1563 [03:38<10:05,  1.90it/s, accuracy=0.689, cost=1.3] IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "minibatch loop: 100%|██████████| 1563/1563 [14:07<00:00,  1.84it/s, accuracy=0.784, cost=0.813]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.96it/s, accuracy=0.532, cost=2.93]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 1.257887, training avg acc 0.695171\n",
      "epoch 20, testing avg loss 3.762570, testing avg acc 0.473888\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [00:35<00:00,  1.12it/s]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.1784567"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
